﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="FeedbackPresenter.cs" company="JDML Consulting Ltd.">
//   Copyright 2011 Photon Project - http://photon.codeplex.com
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Photon.Windows.Input
{
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Controls.Primitives;

    public class FeedbackPresenter : IFeedbackPresenter
    {
        public bool CanUpdateIsEnabled { get; set; }

        public FeedbackPresenter()
        {
            CanUpdateIsEnabled = true;
        }

        public void ProvideFeedback(FrameworkElement element, object obj)
        {
            var method = obj as InvokeMethod;
            if (method != null)
            {
                UpdateControl(element as Control, method.CanExecute);
                if (method.MethodBinding != null)
                {
                    var button = element as ButtonBase;
                    if (button != null && button.ReadLocalValue(ContentControl.ContentProperty) == DependencyProperty.UnsetValue)
                    {
                        button.Content = method.MethodBinding.DisplayName;
                    }
                }
            }
        }

        public void Reset(FrameworkElement element, object obj)
        {
            var method = obj as InvokeMethod;
            if (method != null)
            {
                UpdateControl(element as Control, null);
            }
        }

        private void UpdateControl(Control control, bool? isEnabled)
        {
            if (control != null && CanUpdateIsEnabled)
            {
                if (isEnabled == null)
                {
                    control.ClearValue(Control.IsEnabledProperty);
                }
                else
                {
                    control.IsEnabled = isEnabled.Value;
                }
            }
        }

        public static IFeedbackPresenter Default = new FeedbackPresenter();
    }
}